package com.joke.praser;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

public class HttpUtils {

	private static final String tag = "HttpUtils";

	private static final int DEFAULT_BUFFER_SIZE = 8192;

	/**
	 * 下载数据
	 * 
	 * @param url
	 * @return
	 */
	public static String httpGet(String url) {

		DefaultHttpClient httpclient = new DefaultHttpClient();
		try {
			HttpGet httpget = new HttpGet(url);
			httpget.addHeader("User-Agent", "ie 6");
			HttpResponse response = httpclient.execute(httpget);
			HttpEntity entity = response.getEntity();
			return generateString(entity.getContent());
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}

	}
	
	/**
	 * 下载数据
	 * 
	 * @param url
	 * @return
	 */
	public static InputStream httpGetIS(String url) {

		DefaultHttpClient httpclient = new DefaultHttpClient();
		try {
			HttpGet httpget = new HttpGet(url);
			httpget.addHeader("User-Agent", "ie 6");
			HttpResponse response = httpclient.execute(httpget);
			HttpEntity entity = response.getEntity();
			return entity.getContent();
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}

	}

	private static String generateString(InputStream stream) {
		StringBuilder sb = new StringBuilder();
		InputStreamReader reader = null;
		try {
			reader = new InputStreamReader(stream, "utf-8");
			BufferedReader buffer = new BufferedReader(reader);
			String cur;
			while ((cur = buffer.readLine()) != null) {
				sb.append(cur + "\n");
			}

		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
			return null;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		} finally {
			if (reader != null) {
				try {
					reader.close();
					reader = null;
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (stream != null) {
				try {
					stream.close();
					stream = null;
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

		return sb.toString();
	}

}
